<template>
  <div>
    {{imgLoadPercent }}

 <input @change="uploadInputchange"  id="uploadFileInput" type="file" >
  </div>
</template>

<script>
import axios from 'axios'
export default {
data() {
    return {
        uptoken:'',
        imgLoadPercent:'',
    }
},
methods:{
    get_token(){

        axios.get('http://localhost:8000/qiniu/').then((result) =>{
        console.log(result);
        this.uptoken = result.data.uptoken;
        });
        },
    //触发input change事件
    uploadInputchange(){
        let file = document.getElementById("uploadFileInput").files[0];   //选择的图片文件
        this.get_token();
        this.uploadImgToQiniu(file);
    },
    //上传图片到七牛
    uploadImgToQiniu(file){

        console.log(this.uptoken);

        const axiosInstance = axios.create({withCredentials: false});    //withCredentials 禁止携带cookie，带cookie在七牛上有可能出现跨域问题
        let data = new FormData();
        data.append('token',this.uptoken);     //七牛需要的token
        data.append('file', file);
        axiosInstance({
            method: 'POST',
            url: 'http://up-z1.qiniu.com/',  //上传地址，华北的空间是up-z1.qiniu.com
            data: data,
            timeout:3000000,      //超时时间，因为图片上传有可能需要很久
            onUploadProgress: (e)=> {
                //imgLoadPercent 是上传进度，可以用来添加进度条


                var complete = (e.loaded / e.total);

                if (complete < 1) {
                
                    this.imgLoadPercent = (complete *100).toFixed(2)+ '%';

                }


            },
        }).then(data =>{
           console.log(data);
           this.imgLoadPercent = '100%';
        }).catch(function(err) {
            //上传失败
        });
    }
}
}
</script>

<style>

</style>